# -*- coding: utf-8 -*-
import wsgiref.handlers
import cgi
import re
import datetime
import base64
import urllib
import os

from datetime import *

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import memcache

from google.appengine.ext.webapp import template

from xml.etree.ElementTree import fromstring

import urllib


class GetNicoLive(webapp.RequestHandler):
  def get(self):
    keyword = self.request.get('k')
    callback = self.request.get('jsoncallback')
    if (
        (keyword == "")             |
        (callback == "")            |
        (callback.find('(') != -1)  |
        (callback.find(';') != -1)  |
        (callback.find(')') != -1)  |
        (callback.find('<') != -1)  |
        (callback.find('>') != -1)  |
        (callback.find('=') != -1)
      ):
      return
    
    cache = memcache.get(key='nicodic_%s' % keyword)
    if (cache):
      self.response.out.write(cache.replace('cb(',callback+'('))
    else:
      url = "http://api.nicodic.jp/e/cb/"+urllib.quote(keyword.encode('utf-8'))+"(%E7%94%9F%E6%94%BE%E9%80%81%E4%B8%BB)/"+urllib.quote(keyword.encode('utf-8'))
      content = urlfetch.fetch(url).content
      memcache.set(key='nicodic_%s' % keyword, value= content, time=3600)
      self.response.out.write(content.replace('cb(',callback+'('))

def main():
  application = webapp.WSGIApplication( [('/nicodic', GetNicoLive)],
                                        debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
  main()
